<template>
  <!-- 富文本组件封装、绑有多图片上传、视频上传、文件上传：一个页面多个富文本别用id -->
  <div :class="[editorName, 'editor-box']">
    <quill-editor
      v-model="childctt"
      v-loading="box_loading"
      :ref="editorName"
      :element-loading-text="box_loading_txt"
      :options="editorOption"
      :class="[hghSize, 'my-editor']"
      @change="onEditorChange($event)"
    >
    </quill-editor>

    <el-upload
      style="display: none;"
      class="avatar-uploader"
      :limit="limit"
      multiple
      action="xxx"
      :before-upload="beforeAvatarUpload"
      :http-request="customUpload"
      :file-list="filelist"
      list-type="picture-card"
      :show-file-list="true"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import { getQnToken } from '@/api/user'
export default {
  model: {
    prop: 'content',
    event: 'contentEvent',
  },
  props: {
    content: '',
    // 必传：编辑器的名，不然某页多个编辑器，不能保证各自独立运行
    editorName: {
      type: String,
      default: '',
    },
    // 必传：不然高度样式错乱问题不好处理
    hghSize: {
      type: String,
      default: 'hghSize300',
    },
    limit: {
      type: Number,
      default: 9,
    },
  },
  data() {
    var _this = this
    return {
      box_loading: false,
      box_loading_txt: '',
      progressPercent: 0,
      childctt: '',
      editorOption: {
        placeholder: '请输入将编辑的内容',
        theme: 'snow',
        modules: {
          // 工具栏
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              [{ list: 'ordered' }, { list: 'bullet' }],
              [{ indent: '-1' }, { indent: '+1' }],
              [{ direction: 'rtl' }],
              [{ header: [1, 2, 3, 4, 5, false, 6] }], // [{'header': 1}, {'header': 2}],
              [{ align: [] }],
              // [{'size': ['huge','large',  false, 'small']}],
              [{ color: [] }, { background: [] }], // [{ 'font': [] }],
              ['link', 'image', 'voice', 'video', 'upload'], // , 'emoji'
              ['blockquote', 'code-block'],
              [{ script: 'sub' }, { script: 'super' }],
              ['clean'],
              [
                {
                  size: [
                    '12px',
                    '13px',
                    '14px',
                    '15px',
                    '16px',
                    '17px',
                    '18px',
                    '19px',
                    '20px',
                    '21px',
                    '22px',
                    '23px',
                    '24px',
                    '25px',
                    '26px',
                  ],
                },
              ],
            ],
            handlers: {
              image: function(value) {
                if (value) {
                  document
                    .querySelector(
                      '.' + _this.editorName + ' .avatar-uploader input'
                    )
                    .click()
                } else {
                  _this.quill.format('image', false)
                }
              },
              voice: function(value) {
                if (value) {
                  document
                    .querySelector(
                      '.' + _this.editorName + ' .avatar-uploader input'
                    )
                    .click()
                } else {
                  _this.quill.format('voice', false)
                }
              },
              video: function(value) {
                if (value) {
                  document
                    .querySelector(
                      '.' + _this.editorName + ' .avatar-uploader input'
                    )
                    .click()
                } else {
                  _this.quill.format('video', false)
                }
              },
              upload: (value) => {
                if (value) {
                  document
                    .querySelector(
                      '.' + _this.editorName + ' .avatar-uploader input'
                    )
                    .click()
                }
              },
            },
          },
        },
      },
      uploadUrl: 'https://upload-z2.qiniup.com',
      uploadData: {
        key: '', // -图片名
        token: '', // -七牛token
      },
      filelist: [],
    }
  },
  created() {
    this.$nextTick(() => {
      this.childctt = this.content
    })
  },
  mounted() {
    this.getQnToken()
  },
  methods: {
    /**
     * 富文本组件在编辑时，要把改变的值，同步丢到父层v-model的变量
     */
    onEditorChange(txt) {
      this.$emit('contentEvent', txt.html)
    },
    /**
     * 获取七牛云的 token
     */
    getQnToken: function() {
      getQnToken({}).then((res) => {
        res = res.data
        if (res) {
          localStorage.setItem('qToken', JSON.stringify(res.token))
          this.uploadData.token = res.token
        }
      })
    },

    // -自定义文件上传
    customUpload(param) {
      this.box_loading = true

      const file = param.file
      // 通过 FormData 对象上传文件
      const form = new FormData()
      form.append('file', file)
      form.append('key', this.uploadData.key)
      form.append('token', this.uploadData.token)
      this.$axios
        .post(this.uploadUrl, form, {
          headers: { 'Content-Type': 'multipart/form-data' },
          onUploadProgress: (event) => {
            event.percent = Math.floor((event.loaded / event.total) * 100)
            this.progressPercent = event.percent
            this.box_loading_txt = '上传进度 ' + event.percent + '%'
          },
        })
        .then((res) => {
          if (this.progressPercent >= 100) {
            this.progressPercent = 0
            this.box_loading_txt = '上传进度 0%'
          }

          var imgUrl = this.$QNIMAGE + res.data.key
          var quill = this.$refs[this.editorName].quill // 获取富文本组件实例
          var length = quill.getSelection().index // 获取光标所在位置

          if (file.type.indexOf('image') !== -1) {
            quill.insertEmbed(length, 'image', imgUrl) // 插入图片
            quill.setSelection(length + 1) // 调整光标到最后
          } else if (file.type.indexOf('audio') !== -1) {
            quill.insertEmbed(length, 'customAudio', { url: imgUrl }, 'api')
            quill.setSelection(length + 1)
          } else if (file.type.indexOf('video') !== -1) {
            quill.insertEmbed(length, 'video', imgUrl)
            quill.setSelection(length + 1)
          } else if (
            file.name.indexOf('.doc') !== -1 ||
            file.name.indexOf('.pdf') !== -1
          ) {
            const fileNameLength = file.name.length
            quill.insertEmbed(
              length,
              'link',
              {
                href: imgUrl,
                innerText: file.name,
                id: 'id-' + file.uid,
                dataValue: file.uid,
              },
              'api'
            )
            quill.setSelection(length + fileNameLength) // 调整光标到最后
          }
          this.quillUpdateImg = false // 取消上传动画
          this.filelist = [] // 限制一张，传完就清
          this.box_loading = false
        })
        .catch((err) => {
          this.box_loading = false
        })
    },

    /**
     * 上传 前置 判断
     */
    beforeAvatarUpload(file) {
      const fileType = file.type

      if (fileType.indexOf('image') !== -1) {
        const val = file.name
        const suffix = val.substring(val.lastIndexOf('.') + 1, val.length)
        this.uploadData.key =
          new Date().format('yyyyMMdd') + '/' + file.uid + '.' + suffix
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG && !isPNG) {
          this.$message.error('图片要求是 JPG/PNG 格式!')
          return false
        }
        if (!isLt2M) {
          this.$message.error('图片大小不能超过 2MB!')
          return false
        }
      } else if (fileType.indexOf('audio') !== -1) {
        const val = file.name
        const suffix = val.substring(val.lastIndexOf('.') + 1, val.length)
        this.uploadData.key =
          new Date().format('yyyyMMdd') + '/' + file.uid + '.' + suffix
        const isMP3 = suffix === 'mp3'
        const isLt50M = file.size / 1024 / 1024 < 10
        if (!isMP3) {
          this.$message.error('音频要求是 MP3 格式!')
          return false
        }
        if (!isLt50M) {
          this.$message.error('音频大小不能超过 10MB!')
          return false
        }
      } else if (fileType.indexOf('video') !== -1) {
        const val = file.name
        const suffix = val.substring(val.lastIndexOf('.') + 1, val.length)
        this.uploadData.key =
          new Date().format('yyyyMMdd') + '/' + file.uid + '.' + suffix
        const isMP4 = file.type === 'video/mp4'
        const isLt50M = file.size / 1024 / 1024 < 20
        if (!isMP4) {
          this.$message.error('视频要求是 MP4 格式!')
          return false
        }
        if (!isLt50M) {
          this.$message.error('视频大小不能超过 20MB!')
          return false
        }
      } else if (
        file.name.indexOf('.doc') !== -1 ||
        file.name.indexOf('.pdf') !== -1
      ) {
        const val = file.name
        const suffix = val.substring(val.lastIndexOf('.') + 1, val.length)
        this.uploadData.key =
          new Date().format('yyyyMMdd') + '/' + file.uid + '.' + suffix
        const isLt50M = file.size / 1024 / 1024 < 10
        if (!isLt50M) {
          this.$message.error('文档大小不能超过 10MB!')
          return false
        }
      } else {
        this.$message.error('只允许上传图片、音频/视屏、WORD/PDF文件!')
        return false
      }
    },

    /* 报错提示 */
    // handleError: function(res) {

    //   alert(res)
    // },
    /* 上传回调 */
    // handleAvatarSuccess(res, file, list) {

    //   this.fileQuill = list.map(item => {
    //     item.name = this.$IMAGEURL + item.response.key
    //     item.url = this.$IMAGEURL + item.response.key
    //     return item
    //   })
    //   // 拼接出上传的图片在服务器的完整地址
    //   const imgUrl = this.fileQuill[0].url
    //   // 获取富文本组件实例
    //   const quill = this.$refs[this.editorName].quill
    //   // 获取光标所在位置
    //   const length = quill.getSelection().index
    //   // 插入图片  res.info为服务器返回的图片地址
    //   quill.insertEmbed(length, 'image', imgUrl)
    //   // 调整光标到最后
    //   quill.setSelection(length + 1)
    //   // 取消上传动画
    //   this.quillUpdateImg = false
    //   this.filelis = [] // 限制一张，传完就清
    // }
  },
}
</script>

<style lang="scss" scoped>
.hghSize100 /deep/ .ql-container {
  height: 100px;
}
.hghSize200 /deep/ .ql-container {
  height: 200px;
}
.hghSize300 /deep/ .ql-container {
  height: 300px;
}
.hghSize400 /deep/ .ql-container {
  height: 400px;
}
.hghSize500 /deep/ .ql-container {
  height: 500px;
}
.hghSize600 /deep/ .ql-container {
  height: 600px;
}
.editor-box {
  /deep/ .my-editor {
    line-height: normal;
    .ql-container {
      white-space: pre-wrap;
    }
  }
  /deep/ .ql-upload {
    background: url(../../assets/images/editor/pdf.png);
    background-size: 16px 16px;
    background-position: center center;
    background-repeat: no-repeat;
  }
  /deep/ .ql-voice {
    background: url(../../assets/images/editor/voice.png);
    background-size: 16px 16px;
    background-position: center center;
    background-repeat: no-repeat;
  }
}

.editor-box {
  /deep/ em {
    font-style: italic;
  }
  /deep/ strong {
    font-weight: bold;
  }
  /deep/ u {
    text-decoration: underline;
    font-weight: inherit;
  }

  /* 字号 */
  /deep/ .ql-snow .ql-picker.ql-expanded .ql-picker-options {
    height: 300px;
    overflow: auto;
  }
  // /deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='10px']::before,
  // /deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='10px']::before {
  //   content: '字号10px' !important;
  // }
  // /deep/ .ql-snow .ql-picker.ql-size .ql-picker-label[data-value='11px']::before,
  // /deep/ .ql-snow .ql-picker.ql-size .ql-picker-item[data-value='11px']::before {
  //   content: '字号11px' !important;
  // }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='12px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='12px']::before {
    content: '字号12px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='13px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='13px']::before {
    content: '字号13px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='14px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='14px']::before {
    content: '字号14px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='15px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='15px']::before {
    content: '字号15px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='16px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='16px']::before {
    content: '字号16px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='17px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='17px']::before {
    content: '字号17px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='18px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='18px']::before {
    content: '字号18px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='19px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='19px']::before {
    content: '字号19px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='20px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='20px']::before {
    content: '字号20px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='21px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='21px']::before {
    content: '字号21px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='22px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='22px']::before {
    content: '字号22px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='23px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='23px']::before {
    content: '字号23px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='24px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='24px']::before {
    content: '字号24px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='25px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='25px']::before {
    content: '字号25px' !important;
  }
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-label[data-value='26px']::before,
  /deep/
    .ql-snow
    .ql-picker.ql-size
    .ql-picker-item[data-value='26px']::before {
    content: '字号26px' !important;
  }

  /* 标题 */
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-label::before,
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-item::before {
    content: '默认13px' !important;
  }
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='1']::before,
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='1']::before {
    content: '标题26px' !important;
  }
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='2']::before,
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='2']::before {
    content: '标题24px' !important;
  }
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='3']::before,
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='3']::before {
    content: '标题18px' !important;
  }
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='4']::before,
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='4']::before {
    content: '标题16px' !important;
  }
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='5']::before,
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='5']::before {
    content: '标题14px' !important;
  }
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='6']::before,
  /deep/ .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='6']::before {
    content: '标题12px' !important;
  }
  /deep/ .ql-editor h1 {
    font-size: 26px !important;
  }
  /deep/ .ql-editor h2 {
    font-size: 24px !important;
  }
  /deep/ .ql-editor h3 {
    font-size: 18px !important;
  }
  /deep/ .ql-editor h4 {
    font-size: 16px !important;
  }
  /deep/ .ql-editor h5 {
    font-size: 14px !important;
  }
  /deep/ .ql-editor h6 {
    font-size: 12px !important;
  }
}
</style>
